package fun.xinnix.websocket.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import fun.xinnix.websocket.domain.MessageType;
import fun.xinnix.websocket.domain.SendMessage;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class WebsocketUtils {

    private static WebsocketUtils websocketUtils;

    private WebsocketUtils() {
    }

    public static WebsocketUtils getInstance() {
        if (websocketUtils == null) {
            websocketUtils = new WebsocketUtils();
        }
        return websocketUtils;
    }

    public void sendMessageMsg(SendMessage msg) {
        if (msg == null || StringUtils.isBlank(msg.getToUserId())) {
            log.warn("信息或者用户id为空，无法发送通知");
            return;
        }
        for (Channel channel : ChannelHandlerPool.channelGroup) {
            String userIdByChannel = ChannelHandlerPool.getUserIdByChannel(channel);
            String s = userIdByChannel.split("-")[0];
            if (msg.getToUserId().equals(s)) {
                channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(msg)));
            }
        }
    }

    /**
     * 连接成功给客户端发送消息
     */
    public void sendMessage(String msg, String corrUserId) {
        List<Channel> channelList = ChannelHandlerPool.getChannelByUserId(corrUserId);
        for (Channel channel : channelList) {
            channel.writeAndFlush(new TextWebSocketFrame(msg));
            log.info("发送给用户" + msg);
        }
    }


    public void SendHeartbeat(Channel channel, String toUserId) {
        SendMessage msg = new SendMessage();
        msg.setToUserId(toUserId);
        msg.setMessageType(MessageType.HEARTBEAT);
        msg.setData("ok");
        channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(msg)));

    }
}
